<template>
    <div class="main-content">
        <!--        //上方显示框-->
        <div class="user-info-container" v-for="(supplier, index) in suppliers" @click="showSupplierInfo(supplier,index)" :key="supplier.id">
            <div class="description-title">
                <span>供应商信息(准入评分)</span>
            </div>
            <el-divider class="title-divider" direction="horizontal"></el-divider>
            <el-descriptions :column="3">
                <el-descriptions-item label="供应商编码">{{supplier.supplierCode}}</el-descriptions-item>
                <el-descriptions-item label="供应商名称">{{ supplier.supplierName }}</el-descriptions-item>
                <el-descriptions-item label="供应商准入编码">{{supplier.supplierNum}}</el-descriptions-item>
                <el-descriptions-item label="备注">
                    <!-- 根据供应商的状态显示不同的备注 -->
                    <template v-if="supplier.supplierState === '潜在供应商'">
                        <el-tag size="small">待审核</el-tag>
                    </template>
                    <template v-else-if="supplier.supplierState === '合格供应商'">
                        <el-tag size="small">待签约</el-tag>
                    </template>
                </el-descriptions-item>
                <el-descriptions-item label="联系地址">{{supplier.supplierAddress}}</el-descriptions-item>
            </el-descriptions>
        </div>
        <div class="user-info-container" v-for="(waitsupplier, index) in waitsuppliers" @click="handelShowSupplierEnterInfo(waitsupplier,index)">
            <div class="description-title">
                <span>供应商准入审批</span>
            </div>
            <el-divider class="title-divider" direction="horizontal"></el-divider>
            <el-descriptions :column="3">
                <el-descriptions-item label="供应商编码">{{waitsupplier.supplierCode}}</el-descriptions-item>
                <el-descriptions-item label="供应商名称">{{ waitsupplier.supplierName }}</el-descriptions-item>
                <el-descriptions-item label="供应商准入编码">{{waitsupplier.supplierNum}}</el-descriptions-item>
                <el-descriptions-item label="备注">
                    <!-- 根据供应商的状态显示不同的备注 -->
                    <template v-if="waitsupplier.supplierState === '潜在供应商'">
                        <el-tag size="small">待审核</el-tag>
                    </template>
                    <template v-else-if="waitsupplier.supplierState === '合格供应商'">
                        <el-tag size="small">待签约</el-tag>
                    </template>
                </el-descriptions-item>
                <el-descriptions-item label="联系地址">{{waitsupplier.supplierAddress}}</el-descriptions-item>
            </el-descriptions>
        </div>
        <div class="user-info-container" v-for="(waitSignSupplier, index) in waitSignSuppliers" @click="handelShowSupplierSignInfo(waitSignSupplier,index)">
            <div class="description-title">
                <span>供应商签约审批</span>
            </div>
            <el-divider class="title-divider" direction="horizontal"></el-divider>
            <el-descriptions :column="3">
                <el-descriptions-item label="供应商编码">{{waitSignSupplier.supplierCode}}</el-descriptions-item>
                <el-descriptions-item label="供应商名称">{{ waitSignSupplier.supplierName }}</el-descriptions-item>
                <el-descriptions-item label="供应商准入编码">{{waitSignSupplier.supplierNum}}</el-descriptions-item>
                <el-descriptions-item label="备注">
                    <!-- 根据供应商的状态显示不同的备注 -->
                    <template v-if="waitSignSupplier.supplierState === '潜在供应商'">
                        <el-tag size="small">待审核</el-tag>
                    </template>
                    <template v-else-if="waitSignSupplier.supplierState === '合格供应商'">
                        <el-tag size="small">待签约</el-tag>
                    </template>
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <el-dialog
                title="供应商准入发起"
                :visible.sync="dialogVisible"
                width="50%"
                custom-class="supplier-dialog"
                :before-close="handleClose">

            <el-dialog
                    width="50%"
                    title="供应商准入条例"
                    :visible.sync="innerVisible"
                    custom-class="inner-dialog"
                    append-to-body>
                <SupplierEnterRuleBaseView v-if="showSupplierRuleBaseView" @select-clause="handleSelectClause"></SupplierEnterRuleBaseView>
            </el-dialog>
            <div class="form-scroll-container">
                <span style="color:#409EFF">供应商基本信息</span>
                <el-progress :percentage="15" :format="format" :show-text="false"></el-progress>
                <el-form :model="form" >
                    <el-row :gutter="20">
                        <el-col :span="8" >
                            <el-form-item label="供应商编码">
                                <el-input v-model="form.supplierCode" disabled
                                          style="font-size: 14px; font-weight: bold;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" >
                            <el-form-item label="供应商准入编码">
                                <el-input v-model="form.supplierNum" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="供应商名称">
                                <el-input v-model="form.supplierName" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="准入申请时间">
                                <el-date-picker v-model="form.enterTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <span class="bold-text" >供应商基本信息</span>
                <el-table :data="tableData" style="width: 100%; ">
                    <el-table-column prop="supplierCode" label="供应商编码"></el-table-column>
                    <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
                    <el-table-column prop="supplierType" label="供应商分类">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.supplierType === '零件供应商'" type="warning">{{ scope.row.supplierType }}</el-button>
                            <el-button v-else-if="scope.row.supplierType === '集合供应商'" type="success">{{ scope.row.supplierType }}</el-button>
                            <el-button v-else-if="scope.row.supplierType === '成品供应商'" type="danger">{{ scope.row.supplierType }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="supplierState" label="供应商状态">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.supplierState === '合格供应商'" type="success">{{ scope.row.supplierState }}</el-button>
                            <el-button v-else-if="scope.row.supplierState === '潜在供应商'" type="danger">{{ scope.row.supplierState }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="supplierAddress" label="供应商地址"></el-table-column>
                </el-table>

                <span class="bold-text">供应商财务信息</span>
                <el-table :data="tableData" style="width: 100%;">
                    <el-table-column prop="invoiceHeader" label="发票抬头"></el-table-column>
                    <el-table-column prop="taxNum" label="发票税号"></el-table-column>
                    <el-table-column prop="taxType" label="税种"></el-table-column>
                    <el-table-column prop="taxRate" label="增值税税率%"></el-table-column>
                    <el-table-column prop="bank" label="开户银行"></el-table-column>
                    <el-table-column prop="bankNum" label="开户账号"></el-table-column>
                </el-table>

                <span class="bold-text">供应商联系人信息</span>
                <el-table :data="contactInfo" style="width: 100%;">
                    <el-table-column prop="name" label="姓名"></el-table-column>
                    <el-table-column prop="job" label="职位"></el-table-column>
                    <el-table-column prop="phone" label="电话"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                </el-table>

                <span class="bold-text">供应商资质信息</span>
                <el-table :data="attachments" style="width: 100%; ">
                    <el-table-column prop="name" label="资质/证书名称"></el-table-column>
                    <el-table-column prop="type" label="证书类别"></el-table-column>
                    <el-table-column prop="attachment" label="资质/证书附件">
                        <template slot-scope="scope">
                            <img :src="$basePath+'static/uploadImages/'+scope.row.upFileName" style="max-width: 80px">
                        </template>
                    </el-table-column>
                </el-table>


                <span style="color:#409EFF">供应商准入</span>
                <el-progress :percentage="15" :format="format1" :show-text="false"></el-progress>
                <el-button @click="innerVisible = true" style="margin-top: 20px;"  ><i class="el-icon-s-operation"></i>选择准入条例</el-button>
                <el-form :model="myform" :rules="rules" ref="ruleForm">
                    <el-form-item label="条例名称" :label-width="formLabelWidth">
                        <el-input v-model="myform.clauseName" placeholder="暂无内容" disabled style="width: 50%"></el-input>
                    </el-form-item>
                    <el-form-item label="满分" :label-width="formLabelWidth">
                        <el-input v-model="myform.maxScore" placeholder="暂无内容" disabled style="width: 30%"></el-input>
                    </el-form-item>

                    <el-table :data="clauseItems" style="width: 100%">
                        <el-table-column prop="rules" label="评估项" width="180"></el-table-column>
                        <el-table-column prop="maxScore" label="最高分" width="100"></el-table-column>
                        <el-table-column label="得分*">
                            <template slot-scope="scope">
                                <div class="score-container">
                                    <span class="myScore">*</span>
                                    <el-input
                                            v-model.number="scope.row.score"
                                            size="mini"
                                            @blur="validateScore(scope.row)">
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="评分说明">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.description" size="mini"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="total-score">
                        <span>最终总得分: {{ totalScore }}</span>
                        <span>供应商评级: {{ supplierRating }}</span>
                    </div>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="submitMyForm('ruleForm')">提 交</el-button>
            </div>
        </el-dialog>
        <supplier-enter-approval-view
                :open="openSupplierEnterApprovalDialog"
                :supplier-data="selectedSupplierInfo"
                :table-data="tableData"
                :contact-info="contactInfo"
                :attachments="attachments"
                @close="handleEditDialogClose">
        </supplier-enter-approval-view>
        <SupplierSignView
                :open="openSupplierSignApprovalDialog"
                :supplier-data="selectedSupplierInfo"
                :table-data="tableData"
                @close="handleEditDialogClose"
        >
        </SupplierSignView>
    </div>
</template>

<script>
    import SupplierEnterRuleBaseView from "@/views/manage/messages/SupplierEnterRuleBaseView";
    import SupplierEnterApprovalView from "@/views/manage/messages/components/SupplierEnterApprovalView";
    import SupplierSignView from "@/views/manage/messages/components/SupplierSignView";
    export default {
        name: "ToDoList",
        components: {SupplierEnterApprovalView,
            SupplierEnterRuleBaseView,
            SupplierSignView,
        },
        data() {
            return {
                components: {
                    SupplierEnterRuleBaseView,
                    SupplierEnterApprovalView
                },
                searchQuery:'',
                suppliers: [],
                waitsuppliers:[],
                waitSignSuppliers:[],
                dialogVisible: false,
                innerVisible: false,
                showSupplierRuleBaseView:true,
                form: {
                    supplierId:'',
                    supplierCode: '',
                    supplierNum: '',
                    supplierName: '',
                    enterTime: '',
                    supplierType: '',
                    supplierState: '',
                    supplierAddress: '',
                    invoiceHeader:'',
                    taxNum:'',
                    taxType:'',
                    taxRate:'',
                    bank:'',
                    bankNum:'',

                },
                myform: {
                    ruleId:'',
                    supplierId:'',
                    clauseName: '',
                    maxScore: '',
                    supplierRating:'',
                    clauseItems: []
                },
                formLabelWidth: '120px',
                tableData: [], // 表格数据
                contactInfo:[],
                attachments:[],
                clauseItems: [],
                rules: {}, // 其他静态规则可以在这里定义
                supplierScores:[],
                openSupplierEnterApprovalDialog:false,
                openSupplierSignApprovalDialog:false,
                selectedSupplierInfo: {
                    supplierId:'',
                    supplierCode: '',
                    supplierNum: '',
                    supplierName: '',
                    enterTime: '',
                    supplierType: '',
                    supplierState: '',
                    supplierAddress: '',
                    invoiceHeader:'',
                    taxNum:'',
                    taxType:'',
                    taxRate:'',
                    bank:'',
                    bankNum:'',
                },
            };
        },
        computed: {
            totalScore() {
                return this.clauseItems.reduce((sum, item) => sum + (item.score || 0), 0);
            },
            maxScore(){
                return this.myform.maxScore;
            },
            supplierRating() {
                const total = this.totalScore;
                const maxScore=this.maxScore;
                if (total >= maxScore*(0.8)) return '一级供应商';
                else if (total >= maxScore*(0.75)) return '二级供应商';
                else if (total >=maxScore*(0.60) ) return '三级供应商';
                else return '不合格';
            },
        },
        created() {
            this.getSupplierInnerList();
            this.getWaitApprovalList();
            this.getApprovalSignWaitList();
        },
        methods: {

            handleEditDialogClose(){
                console.log("close..............")
                this.openSupplierEnterApprovalDialog=false;
                this.openSupplierSignApprovalDialog=false;
            },
            //打分的验证
            validateScore( item) {
                // 检查得分是否为空
                if (item.score === undefined || item.score === null || item.score === '') {
                    this.$message.error('得分不能为空');
                    return false;
                }
                // 检查得分是否超过了最高分
                if (item.score > item.maxScore) {
                    this.$message.error('得分不能超过最高分');
                    return false;
                }
                return true;
            },
            submitMyForm(formName) {
                if (!this.myform.selectedClause) {
                    this.$message.error('请选择准入条例');
                    return;
                }
                // 如果选择了准入条例，继续验证评分项
                let allValid = true;
                for (let item of this.clauseItems) {
                    if (!this.validateScore(item)) {
                        allValid = false;
                        break;
                    }
                }
                if (!allValid) {
                    this.$message.error('请检查评分项');
                    return;
                }
                const formData = {
                    supplierId: this.form.supplierId, // 假设 supplierId 在 form 对象中
                    clauseName: this.myform.clauseName,
                    maxScore: this.myform.maxScore,
                    clauseItems: this.clauseItems,
                    supplierRating:this.supplierRating,
                    ruleId: this.myform.ruleId,
                };

                // 发送 AJAX 请求到后端
                axios.post('/manage/supplierEnterRoleScores/addScores', formData)
                    .then(response => {
                        // 处理响应
                        console.log('Response from server:',formData);
                        this.$message.success('提交成功');
                        this.myform.selectedClause = null;
                        this.myform.clauseName = '';
                        this.myform.maxScore = '';
                        this.clauseItems = [];
                        this.dialogVisible = false;
                        this.getSupplierInnerList();
                    })
                    .catch(error => {
                        // 处理错误
                        console.error('Error submitting form:', error);
                        this.$message.error('提交失败，请重试');
                    });
                this.getSupplierInnerList();

                // // 如果所有评分项都通过了验证，继续提交表单
                // console.log('提交表单', this.myform);
                // this.dialogVisible = false;
            },
            format(percentage) {
                return percentage === 100 ? '满' : `${percentage}%`;
            },
            format1(percentage) {
                return percentage === 100 ? '满' : `${percentage}%`;
            },
            handleTabClick(tab) {
                this.activeTab = tab;
                console.log('Tab clicked:', tab);
            },
            handleSearch() {
                console.log('Search:', this.searchQuery);
            },
            handleFilter() {
                console.log('Filter clicked');
            },
            handleSort() {
                console.log('Sort clicked');
            },
            handleSubmit() {
                console.log('Submit clicked');
            },
            handleClose(done) {
                this.$confirm('关闭后数据将不会保存，确认关闭吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(_ => {
                        // 用户确认关闭，清空数据
                        this.myform.selectedClause = null;
                        this.myform.clauseName = '';
                        this.myform.maxScore = '';
                        this.clauseItems = [];
                        // 关闭对话框
                        this.dialogVisible = false;
                        done();
                    })
                    .catch(_ => {
                    });
            },
            submitForm() {
                // 提交表单的逻辑
                console.log('提交表单', this.myform);
                this.dialogVisible = false;
            },
            getSupplierInnerList(){
                this.$axios.get("manage/supplier/innerList").then(
                    response=>{
                        this.suppliers=response.data.suppliers;
                    }
                )
            },
            getWaitApprovalList(){
                this.$axios.get("manage/approval/list").then(
                    response=>{
                        this.waitsuppliers=response.data.waitApprovalenterSupplier;
                    }
                )
            },
            getApprovalSignWaitList(){
                this.$axios.get("manage/approval/approvalSignList").then(
                    response=>{
                        this.waitSignSuppliers=response.data.approvalSignWaitList;
                        // console.log(this.waitSignSuppliers);
                    }
                )
            },
            showSupplierInfo(supplier) {
                this.form = { ...supplier }; // 将供应商信息复制到表单模型
                this.dialogVisible = true; // 显示 dialog
                this.tableData = [this.form];
                this.handleFindContactinfo(supplier.id);
                this.handleAttachments(supplier.id);
                this.form.supplierId = supplier.id;
                this.selectedSupplierInfo =  { ...supplier };

            },
            handelShowSupplierEnterInfo(supplier){
                this.form = { ...supplier }; // 将供应商信息复制到表单模型
                this.openSupplierEnterApprovalDialog=true;
                this.selectedSupplierInfo= { ...supplier };
                this.tableData = [this.form];
                this.contactInfo=this.handleFindContactinfo(supplier.id);
                this.attachments=this.handleAttachments(supplier.id);
            },
            handelShowSupplierSignInfo(supplier){
                this.form = { ...supplier }; // 将供应商信息复制到表单模型
                this.openSupplierSignApprovalDialog=true;
                this.selectedSupplierInfo= { ...supplier };
                this.tableData = [this.form];
                this.contactInfo=this.handleFindContactinfo(supplier.id);
                this.attachments=this.handleAttachments(supplier.id);
            },
            //通过供应商的id查找相应的信息联系人信息，资质信息
            handleFindContactinfo(id){
                this.$axios.get("manage/contactinfo/"+id).then(
                    response=>{
                        this.contactInfo=[response.data.contactinfo.contactinfo];
                    }
                )
            },
            handleAttachments(id){
                this.$axios.get("manage/attachment/"+id).then(
                    response=>{
                        this.attachments=[response.data.attachment.attachment];
                    }
                )
            },
            handleSelectClause(selectedClause) {
                this.myform.selectedClause = selectedClause;
                this.myform.ruleId=selectedClause.id;
                this.myform.clauseName = selectedClause.supplierEnterRule.name;
                this.myform.maxScore = selectedClause.supplierEnterRule.totalScore;
                this.clauseItems = selectedClause.supplierEnterRuleDataList;
                this.innerVisible=false;
            },
        }
    };
</script>

<style scoped>
    .total-score {
        margin-top: 20px; /* 在表格下方添加一些空间 */
        font-size: 16px; /* 字体大小 */
        font-weight: bold; /* 字体加粗 */
        color: #333; /* 字体颜色 */
    }

    .total-score span {
        margin-right: 10px; /* 标签和值之间的空间 */
    }
    .bold-text {
        display: block; /* 确保span占据一整行 */
        margin-top: 20px; /* 设置上边距，数值可以根据需要调整 */
        font-weight: bold; /* 如果需要，可以添加粗体样式 */
    }
    .myScore{
        color: red; /* 星号颜色为红色，表示必填 */
        margin-right: 4px; /* 在星号和输入框之间添加一些空间 */
    }
    .score-container {
        display: flex;
        align-items: center; /* 垂直居中对齐 */
    }

    .header-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 16px;
        background-color: #F2F6FC;
        border-bottom: 1px solid #ebebeb;
    }


    .tabs-container {
        display: flex;
        align-items: center;
    }

    .tab-button {
        margin-right: 8px;
        border-radius: 20px;
        padding: 8px 16px;
        font-size: 14px;
        line-height: 1.5;
        white-space: nowrap;
    }

    .tab-button.active {
        background-color: #2d8cf0;
        color: #fff;
        border-color: #2d8cf0;
    }

    .search-container {
        margin-left: 16px;
    }

    .search-box {
        width: 250px;
        border-radius: 20px;
        background-color: #f3f3f3;
        border: 1px solid #ebebeb;
    }

    .filter-container,
    .sort-container,
    .submit-container {
        margin-left: 16px;
    }

    .filter-button,
    .sort-button,
    .submit-button {
        border-radius: 20px;
        padding: 8px 16px;
        font-size: 14px;
        line-height: 1.5;
        white-space: nowrap;
    }

    .filter-button {
        background-color: #e6f7ff;
        color: #2d8cf0;
        border-color: #e6f7ff;
    }

    .sort-button {
        background-color: #f9f9f9;
        color: #606266;
        border-color: #ebebeb;
    }

    .submit-button {
        background-color: #f9f9f9;
        color: #606266;
        border-color: #ebebeb;
    }
    .user-info-container {
        padding: 16px;
        margin-bottom: 16px;
        border: 1px solid #ebebeb;
        background-color: #fff;
        border-radius: 4px;
    }

    .description-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
    }

    .description-title span {
        font-size: 16px;
        font-weight: bold;
    }

    .title-divider {
        margin-top: 8px; /* 调整与标题的距离 */
        margin-bottom: 8px; /* 调整与内容的距离 */
        border-top: 1px solid #ebebeb; /* 自定义分割线样式 */
    }

    .el-descriptions {
        border-bottom: 1px solid #ebebeb;
        padding-bottom: 16px;
    }

    .el-descriptions__item {
        margin-bottom: 8px;
    }

    .el-descriptions__item-label {
        font-weight: bold;
        color: #606266;
    }

    .el-descriptions__item-content {
        color: #909399;
    }

    .el-tag {
        margin-left: 8px;
    }
    .supplier-dialog {
        /* 对话框整体样式 */
        border-radius: 8px;
    }

    .dialog-content {
        /* 对话框内容区域样式 */
        padding: 20px;
    }

    .form-style .el-form-item {
        /* 表单项样式 */
        margin-bottom: 20px;
    }

    .input-style {
        /* 输入框样式 */
        width: 100%;
        border-color: #dcdfe6;
    }

    .table-style {
        /* 表格样式 */
        margin-top: 20px;
    }

    .dialog-footer {
        /* 对话框底部样式 */
        text-align: right;
        padding-top: 10px;
    }
    .form-scroll-container {
        max-height: 400px; /* 根据需要调整高度 */
        overflow-y: auto;
        padding: 10px; /* 可选，根据需要添加内边距 */
        border: 1px solid #dcdfe6; /* 可选，根据需要添加边框 */
        border-radius: 4px; /* 可选，根据需要添加圆角 */
    }

    .dialog-footer .el-button {
        /* 底部按钮样式 */
        margin-left: 10px;
    }
    .inner-dialog {
        border-radius: 8px;
        margin-top: 20px;
        max-height: 400px; /* 设置最大高度 */
        overflow-y: auto; /* 当内容超出时显示滚动条 */
    }
</style>